<?php
class System_Model_AdministratorMapper {
	
	protected $_dbTable;
	
	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	
	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('System_Model_DbTable_Administrator');
		}
		return $this->_dbTable;
	}
	
	
	public function save(System_Model_Administrator $admin){
		$verify=$this->verifyUsername($admin->getUsername());
		if($verify!==true){
			return $verify;
		}
		
		$data=array(
				'username'=>$admin->getUsername(),
				'password'=>md5(md5($admin->getPassword())),
				'role_id'=>1
				);
		$result=$this->getDbTable()->insert($data);
		return isset($result)?true:false;
	}
	
	public function update(System_Model_Administrator $admin){
		if(is_null($admin->getForbidden())){
			$data=array("password"=>md5(md5($admin->getPassword())));
		}else{
			$data=array("forbidden"=>$admin->getForbidden());
		}
		try{
			$result=$this->getDbTable()->update($data,$this->getDbTable()->getAdapter()->quoteInto('id = ?', $admin->getId()));
			return $result;
		}catch(Exception $e){
			return Utils_SQLErrorMsg::formatException($e);
		}
	}
	
	public function findByName($name,System_Model_Administrator $admin){
		$select=$this->getDbTable()->select()->where("username='".$name."'");
		$string=$select->__toString();
		try{
			$result= $this->getDbTable()->fetchAll($select)->toArray();
			if(count($result)){
				$admin->setOptions($result[0]);
			}
			return $admin;
		}catch(Exception $e){
			return Utils_SQLErrorMsg::formatException($e);
		}
	}
	
	public function findAll($curPage=1,$perPage=20){
		$select=$this->getDbTable()->select()
		->limitPage($curPage, $perPage);
		$rows=$this->getDbTable()->getAdapter()->fetchOne("select count(*) from system_user");
		$string=$select->__toString();
		$data=array();
		try{
			$data=$this->getDbTable()->fetchAll($select)->toArray();
		}catch (Exception $e){
			return Utils_SQLErrorMsg::formatException($e);
		}
		$response=new stdClass();
		$response->page=$curPage;
		$response->total=ceil($rows/$perPage);
		$response->records=(int)$rows;
		$response->rows=$data;
		return $response;
	}
	
	public function verifyUsername($username){
		$verify=User_Model_Utils_RegExp::userName($username, "ALL", 6,20);
		if($verify!==true){
			return $verify;
		}else{
			$where=$this->getDbTable()->getAdapter()->quoteInto('username = ?', $username);
			$result=$this->getDbTable()->fetchRow($where);
			if(isset($result)){
				return "用户名已经被注册";
			}else{
				return true;
			}
		}
	}
	
}

?>